<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<!-- 关联信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>关联信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_JobAssignmentId_FormItem" prop="Entity.JobAssignmentId">
								<template #label>
									<WtmLabelTooltip label="分岗申请单号" tooltip="关联的分岗申请单" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.JobAssignmentId" disabled clearable class="width100">
									<el-option
										v-for="item in stateData.AllSysHrJobAssignmentRequestBills"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 人员信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>人员信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.PersonId" disabled clearable class="width100">
									<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" disabled clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" disabled clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EntryRemark_FormItem" prop="Entity.EntryRemark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="分岗备注信息" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.EntryRemark" disabled clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 工作信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :disabled="true" />
						</el-col>
					</el-row>
					<wtm-dept-selector
						v-model="stateData.vmModel.Entity.GroupId"
						label="所属部门"
						:show-position="true"
						v-model:position-id="stateData.vmModel.Entity.JobPositionId"
						position-label="工作岗位"
						:use-row="true"
						:dept-col="12"
						:position-col="12"
						:disabled="true"
						:position-disabled="true"
						:org-id="stateData.vmModel.Entity.OrgId"
					/>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, type ComponentInternalInstance } from 'vue';
import ElMessage from 'element-plus/es/components/message/index';
import { SysHrJobAssignmentRequestBillEntryApi as api } from '/@/views/hr/syshrjobassignmentrequestbillentry/api';
import other from '/@/utils/other';
import { ISysHrJobAssignmentRequestBillEntryVm } from '/@/views/hr/syshrjobassignmentrequestbillentry/api/interface';
import { IViewModel } from '/@/types/common';

// 常量定义

const BUTTON_TEXTS = {
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	BILLS: '/api/SysHrJobAssignmentRequestBillEntry/GetSysHrJobAssignmentRequestBills',
	PERSONS: '/api/SysHrJobAssignmentRequestBillEntry/GetSysPersons',
	POSITIONS: '/api/SysHrJobAssignmentRequestBillEntry/GetSysJobPositions',
	GROUPS: '/api/SysHrJobAssignmentRequestBillEntry/GetSysGroups',
	ORGS: '/api/SysHrJobAssignmentRequestBillEntry/GetSysOrgs',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrJobAssignmentRequestBillEntryVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			StaffNo: null,
			Name: null,
			JobPositionId: null,
			GroupId: null,
			OrgId: null,
			EntryRemark: null,
			JobAssignmentId: null,
		} as any,
	},
	AllSysHrJobAssignmentRequestBills: [],
	AllSysPersons: [],
	AllSysJobPositions: [],
	AllSysGroups: [],
	AllSysOrgs: [],
});

// 取消
const onClose = () => {
	closeDialog();
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = window.location.search.match(/[?&]id=([^&]*)/)?.[1];

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	try {
		// 加载选择列表数据
		const [bills, persons, positions, groups, orgs] = await Promise.allSettled([
			other.getSelectList(API_ENDPOINTS.BILLS, [], false),
			other.getSelectList(API_ENDPOINTS.PERSONS, [], false),
			other.getSelectList(API_ENDPOINTS.POSITIONS, [], false),
			other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
			other.getSelectList(API_ENDPOINTS.ORGS, [], false),
		]);

		if (bills.status === 'fulfilled') stateData.AllSysHrJobAssignmentRequestBills = bills.value;
		if (persons.status === 'fulfilled') stateData.AllSysPersons = persons.value;
		if (positions.status === 'fulfilled') stateData.AllSysJobPositions = positions.value;
		if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
		if (orgs.status === 'fulfilled') stateData.AllSysOrgs = orgs.value;
	} catch (error) {
		// 静默处理错误
	}
};

// 加载实体数据
const loadEntityData = async () => {
	if (!stateData.vmModel.Entity.ID) {
		return;
	}

	try {
		const response = await api().get(stateData.vmModel.Entity.ID);
		other.setValue(stateData.vmModel, response);
	} catch (error) {
		ElMessage.error('加载数据失败，请重试');
		throw error;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	try {
		// 首先初始化页面数据（获取ID）
		initializePageData();

		// 并行加载选择列表数据和实体数据
		await Promise.all([loadSelectListData(), loadEntityData()]);
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
